window.log = function() {
    //console.log(arguments);
};

/* Gauges needs to be global */
var _gauges = _gauges || [];
/* Expose the background page's window object */
window.$e = chrome.extension.getBackgroundPage();
/* Error messaging */
window.$error = function(message, append) {
    Template('error', {message: message, id: window.location.hash.substr(1)}, function(html) {
        $content[(append) ? 'append' : 'html'](html);
    });
};
window.$loading = function() {
    $content.html('<div class="tac pl"><img src="static/img/load.gif" /></div>');
};
/* Cache object */ 
window.cache = {};

/* Setup Facebook, check login status and permissions */
window.FB = $e.FB;
if(!FB.getAccessToken()) {
    FB.login();
    window.close();
} else {
    FB.getMissingPermissions(function(missing) {
        if(missing && missing.length) {
            require(['alert'], function(alert) {
                var text = "You haven't enabled some permissions needed to make Facebook for Chrome work correctly:" + ' <i class="light">' + missing.join(', ') + '</i>. Click okay below to enable.';
                alert({text: text, title: 'Permissions Warning', fn: function() {
                    FB.login();
                    window.close();
                }});
            });
        }
    });
}

/* Post parser, used all over the place */
window.postParser = function(posts) {
    if(!$.isArray(posts)) { posts = [posts]; }
    $.each(posts, function() {
        this.canLike = true;
        var uid = FB.getUserID(),
            post = this;
        
        /* See if the user likes the post */
        if(this.likes && this.likes.data) {
            $.each(this.likes.data, function() {
                if(this.id == uid) {
                    post.canLike = false;
                    return false;
                }
            });
        }
        
        /* Pretty the timestamp */
        this.ago = moment(new Date(this.updated_time)).fromNow();
        
        /* Pick the correct picture */
        this.picture = (this.link && this.picture) ? this.picture : (this.object_id ? 'https://graph.facebook.com/' + this.object_id + '/picture/?access_token=' + FB.getAccessToken() : false);
        
        if(!this.picture && this.cover_photo) {
            this.picture = 'https://graph.facebook.com/' + this.cover_photo + '/picture?access_token=' + FB.getAccessToken();
        }
        
        if(this.type == 'photo') {
            this.picture = this.picture.replace(/_[nast]\.j/, '_a.j');
        }
        
        /* No pics for videos */
        if(this.type == 'video') {
            this.picture = false;
        }
    });
    
    return posts || [];
};

require(['jquery.min','moment','cache','mustache','template'], function() {
    /* Store the content area globally */
    window.$content = $('#content');
    
    /* Make sure it stays the right size */
    $(window).on('resize', function() {
        window.resizeTo(470,480);
    });
    
    /* Setup nav hovers */
    require(['tips'], function() {
        $('#nav li a').tips();
    }); 
    
    var scrollable = function() {
            var scroll = $('.scroll'),
                height = $(window).height();
                
            $content.height(height - 30);
            if(scroll.length) {
                scroll.height(height - scroll.offset().top);
            }
        };
    
    /* Quickly add profile picture to header */
    (function(src) {
        var img = new Image();
            img.onerror = function() {
                require(['alert'], function(alert) {
                    alert({text: 'Facebook for Chrome is temporarily unavailable because of a Facebook API error', fn: function() {
                        window.close();
                    }});
                });
            }
            img.src = src;
        $('#nav').prepend('<li><a href="#me" data-tip="Your Profile"><img src="' + src + '" class="pic" /></a></li>');
    })('https://graph.facebook.com/me/picture/?access_token=' + FB.getAccessToken());
    
    /* Handle popovers */
    $('#status,#notifications').on('click', function(e) {
        e.preventDefault();
        var id = e.currentTarget.id;
        require([id], function(popover) {
            var current = $('#' + id + '-popover').toggle();
            $('.popover').not(current).hide();
            if(current.is(':visible')) {
                if(popover && 'go' in popover) { popover.go(); }
            }
        });
    });
    
    /* Handle clicks outside of popovers */
    $(document.body).on('click', function(e) {
        if(!$(e.target).closest('.popover,#status,#notifications').length) {
            $('.popover').hide();
        }
    });
    
    /* Add search functionality */
    $('#header').on('keyup', '#search', function() {
        $('#header').off('keyup');
        require(['search'], function(search) {
            search.init();
        });
    });
    
    /* Render Object */
    var render = function(res) {
        $('#footer').delay(750).fadeOut('fast');
        log(res);
        /* If false, show error message */
        if(res === false || res.error) {
            return $error('This content is not accessible from Facebook for Chrome');
        }
        /* If there is a message_count assume it is a thread */
        if(res.message_count) {
            if(res && res.messages && res.messages.data) {
                $.each(res.messages.data, function() { this.ago = moment(new Date(this.created_time)).fromNow(); });
            }
            Template('thread', res, function(html) {
                $content.html(html);
            });
            return;
        }
        /* If there is a type, assume a post */
        if(res.from || res.data) {
            var posts = (res.data) ? postParser(res.data) : postParser(res);
            Template('posts', {posts: posts}, function(html) {
                $content.html(html);
                require(['posts'], function(posts) {
                    posts.listen();
                });
            }, ['likes','comments']);
            return;
        }
        /* If there is a first_name, assume it is a profile */
        if(res.first_name || res.username || res.name || (res.name && res.privacy)) {
            res.link = res.link || 'http://facebook.com/' + res.id;
            require(['profile'], function(profile) {
                profile.go(res);
            });
            return;
        }
        
    };
        
    
    /* When the page changes, change the page */
    $(window).on('hashchange', function() {
        $('#footer').fadeIn('fast').text('Loading ' + window.location.hash);
        /* Clear all event handlers in content */
        var clone = $content.empty().clone();
        $content.replaceWith(clone);
        $content = clone.scrollTop(0,0);
        
        /* Determine page, and load controller */
        switch(window.location.hash) {
            case '#events':
            case '#inbox':
            case '#notifications':
            case '#home':
            case '#photos':
            case '#help':
                require([window.location.hash.substr(1)], function(page) {
                    page.go();
                    $('#footer').delay(500).fadeOut('fast');
                });
            break;
            default:
                $loading();
                if(window.cache[window.location.hash.substr(1)]) {
                    return render(window.cache[window.location.hash.substr(1)]);
                }
                /* Try to pull object from FB */
                FB.api(window.location.hash.substr(1), render);
            break;
        }
        
        /* Try to track a page view */
        try {
            _gauges.push(['track']);
        } catch(e) {}
    });
    
    /* Make sure home is the default page */
    if(!window.location.hash) {
        window.location.hash = 'home';
    } else {
        $(window).triggerHandler('hashchange');
    }
    
    /* Quickly show notifications if there are some unread */
    (function(notifs) {
        if(!notifs || !notifs.data || !notifs.data.length) { return; }
        var unread = $.grep(notifs.data, function(n) {
            return n.unread;
        });
        if(unread.length) {
            $('#notification_count').text(unread.length).show();
            $('#notifications').click();
        }
    })($e.data.notifs);
            
    
    /* When the page loads, start looking for scrollable areas, and resize them */
    scrollable();
    setInterval(scrollable, 100);
   
   $(window).on('keydown', function(e) {
        if(e.which == 27) {
            if($('.popover:visible').length) {
                $('.popover').hide();
                e.preventDefault();
            }
        }
   });
   
   /* Skimlinks */
   $('body').on('click', 'a', function(e) {
        var link = $(e.currentTarget);
        if(link.attr('target') == '_blank') {
            e.preventDefault();
            var url = encodeURIComponent(link.attr('href'));
            var ref = encodeURIComponent('http://64px.com');
            window.open('http://l.64px.com/?id=29228X870093&xs=1&url=' + url + '&sref=' + ref);
            return false;
        }
        return true;
   });
   
   /* Logout */
   $('body').on('click', '#logout', function() {
        var next = encodeURIComponent('http://64px.com/more?t=' + encodeURIComponent('You are now logged out of Facebook'));
        var token = FB.getAccessToken();
        FB.setAccessToken(false);
        window.open('https://www.facebook.com/logout.php?next=' + next + '&access_token=' + token);
   });
});


setTimeout(function() {
      (function() {
        var t   = document.createElement('script');
        t.type  = 'text/javascript';
        t.async = true;
        t.id    = 'gauges-tracker';
        t.setAttribute('data-site-id', '4efe2668f5a1f5158a00000a');
        t.src = 'http://secure.gaug.es/track.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(t, s);
      })();
}, 500);